package com.linkage.jz.bankruptcy.fragment.Main;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.LawDetailActivity;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Project.OtherUserDetailActivity;
import com.linkage.jz.bankruptcy.adapter.CarryOutListViewAdapter;
import com.linkage.jz.bankruptcy.adapter.LawListViewAdapter;
import com.linkage.jz.bankruptcy.bean.CarryOutListInfo;
import com.linkage.jz.bankruptcy.bean.LawListInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserInfo;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.Divider;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.pojo.TempProjectDetail;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * date : 2016/5/24
 * author : lijiawei
 */
public class CarryOutListFrgment extends Fragment implements BGAOnRVItemClickListener, BGAOnRVItemLongClickListener, BGAOnItemChildClickListener, BGAOnItemChildLongClickListener {

    //显示信息
    private TextView text;
    //    private static final String TAG = RecyclerViewDemoActivity.class.getSimpleName();
    private CarryOutListViewAdapter mAdapter;
    private ArrayList<CarryOutListInfo> mData;
    private RecyclerView mDataRv;
    private EditText law_searchtxt;
    private LinearLayout ll_nodata;

    ArrayList<Fragment> fragments = new ArrayList<Fragment>();



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_carryout_list, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        initRecyclerView(view);
//        getData();

    }

    private void init(View view) {
//        text = (TextView) view.findViewById(R.id.fragment_textview);
//        text.setText("GroupChildrenHasBuy");
    }

    private void initRecyclerView(final View view) {
        mDataRv = (RecyclerView) view.findViewById(R.id.rv_recyclerview_data);
//        mDataRv.addItemDecoration(new Divider(getActivity()));
        law_searchtxt = (EditText) view.findViewById(R.id.law_searchtxt);
        ll_nodata =(LinearLayout)view.findViewById(R.id.ll_nodata);
        law_searchtxt.setOnEditorActionListener(new TextView.OnEditorActionListener(){
            @Override

            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {

// TODO Auto-generated method stub

                if(arg1 == EditorInfo.IME_ACTION_SEARCH)

                {
                    InputMethodManager imm = (InputMethodManager) view.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(view.getWindowToken(),0);
                    }
                    mData.clear();
                                mAdapter.notifyDataSetChanged();

                    getData();
//                    Toast.makeText(AddMemberActivity.this,"呵呵",Toast.LENGTH_SHORT).show();

// search pressed and perform your functionality.

                }

                return false;

            }

        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDataRv.setLayoutManager(layoutManager);

        mAdapter = new CarryOutListViewAdapter(mDataRv,getActivity());
        mAdapter.setOnRVItemClickListener(this);
        mAdapter.setOnRVItemLongClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemChildLongClickListener(this);

        mDataRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    mAdapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });
        mData = new ArrayList<CarryOutListInfo>();
//        mData = DataEngine.loadNormalModelDatas();

//        CarryOutListInfo model = new CarryOutListInfo();
////        model.setId(data.getString("id"));
//        model.setTitle("顺丰速运电话");
//        model.setContent("95338");
//        mData.add(model);
//
//        CarryOutListInfo model1 = new CarryOutListInfo();
//        model1.setTitle("中通速递电话");
//        model1.setContent("4008-270-270");
//        mData.add(model1);
//
//        CarryOutListInfo model2 = new CarryOutListInfo();
//        model2.setTitle("宅急送电话");
//        model2.setContent("400-6789-000");
//        mData.add(model2);
//
//        CarryOutListInfo model3 = new CarryOutListInfo();
//        model3.setTitle("邮政包裹/挂号信");
//        model3.setContent("11183");
//        mData.add(model3);
//
//        CarryOutListInfo model4 = new CarryOutListInfo();
//        model4.setTitle("申通快递电话");
//        model4.setContent("95543");
//        mData.add(model4);
//
//        CarryOutListInfo model5 = new CarryOutListInfo();
//        model5.setTitle("圆通速递电话");
//        model5.setContent("95554");
//        mData.add(model5);
//
//        CarryOutListInfo model6 = new CarryOutListInfo();
//        model6.setTitle("天天快递电话");
//        model6.setContent("4001-888-888");
//        mData.add(model6);
//
//
//        CarryOutListInfo model7 = new CarryOutListInfo();
//        model7.setTitle("百世快递电话");
//        model7.setContent("95320");
//        mData.add(model7);
//
//        CarryOutListInfo model8 = new CarryOutListInfo();
//        model8.setTitle("韵达快递电话");
//        model8.setContent("95546");
//        mData.add(model8);
//
//        CarryOutListInfo model9 = new CarryOutListInfo();
//        model9.setTitle("EMS快递电话");
//        model9.setContent("11183");
//        mData.add(model9);
//
//        CarryOutListInfo model10 = new CarryOutListInfo();
//        model10.setTitle("德邦快递电话");
//        model10.setContent("95353");
//        mData.add(model10);
//
//        CarryOutListInfo model11 = new CarryOutListInfo();
//        model11.setTitle("全峰快递电话");
//        model11.setContent("400-100-0001");
//        mData.add(model11);


        mAdapter.setData(mData);
        mDataRv.setAdapter(mAdapter);
        getData();
    }

    @Override
    public void onItemChildClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
            mAdapter.closeOpenedSwipeItemLayoutWithAnim();
            mAdapter.removeItem(position);
        }
    }

    @Override
    public boolean onItemChildLongClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
//            Toast.makeText(getActivity(), "长按了删除 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    private PublicNoticeDialog noticeDialog;
    private  String phone = "";
    public static final int REQUEST_CALL_PERMISSION = 10111; //拨号请求码
    public static final int REQUEST_SMS_PERMISSION = 10112; //拨号请求码
    @Override
    public void onRVItemClick(ViewGroup parent, View itemView, int position) {


        CarryOutListInfo model = mAdapter.getItem(position);
        if(model !=null) {
            phone = model.getPhone();
//            phone = "确定拨打"
            noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener(){

                @Override
                public void onClick(View v) {
                    switch (v.getId()) {
                        case R.id.ll_close:
                            noticeDialog.dismiss();
                            break;
                        case R.id.btn_chancel_notice:

                            if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_SMS_PERMISSION)){

                                try {
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));

                                    Intent intent = new Intent(Intent.ACTION_SENDTO);
                                    Uri data = Uri.parse("smsto:" + phone);
                                    intent.setData(data);
                                    startActivity(intent);

//                                                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+phoneNumber));
//                                                intent.putExtra("sms_body", message);
//                                                startActivity(intent);

                                }catch (Exception ex){
                                    ex.printStackTrace();
                                }
                            }
                            noticeDialog.dismiss();
                            break;

                        case R.id.btn_save_notice:
                            if(!"".equalsIgnoreCase(phone)) {
                                if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_CALL_PERMISSION)){

                                    try {
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));

                                        Intent intent = new Intent(Intent.ACTION_CALL);
                                        Uri data = Uri.parse("tel:" + phone);
                                        intent.setData(data);
                                        startActivity(intent);
                                    }catch (Exception ex){
                                        ex.printStackTrace();
                                    }
                                }
                            }
                            noticeDialog.dismiss();

                            break;
                    }
                }
            }, 2,phone, phone,"发短信","拨打电话");
            noticeDialog.show();


//            LawDetailActivity.start(getActivity(),model.title,model.id,model.content);
        }
//        Toast.makeText(getActivity(), "点击了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ll_close:
                    noticeDialog.dismiss();
                    break;

                case R.id.btn_chancel_notice:
//                   Boolean flag =  noticelxDialog.cb_agree.isChecked();
                    noticeDialog.dismiss();

                    break;

                case R.id.btn_save_notice:
//                    finish();
                    noticeDialog.dismiss();
                    if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_CALL_PERMISSION)){

                        try {
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));

                            Intent intent = new Intent(Intent.ACTION_CALL);
                            Uri data = Uri.parse("tel:" + phone);
                            intent.setData(data);
                            getActivity().startActivity(intent);
                        }catch (Exception ex){
                            ex.printStackTrace();
                        }
                    }
                    break;

            }
        }
    };

    /**
     * 判断是否有某项权限
     * @param string_permission 权限
     * @param request_code 请求码
     * @return
     */
    public boolean checkReadPermission(String string_permission,int request_code) {
        boolean flag = false;
        if (ContextCompat.checkSelfPermission(getActivity(), string_permission) == PackageManager.PERMISSION_GRANTED) {//已有权限
            flag = true;
        } else {//申请权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{string_permission}, request_code);
        }
        return flag;
    }

    /**
     * 检查权限后的回调
     * @param requestCode 请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CALL_PERMISSION: //拨打电话
                if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
                    Toast.makeText(getActivity(),"请允许拨号权限后再试",Toast.LENGTH_SHORT).show();
                } else {//成功
//                    call("tel:"+"10086");
                    Intent intent1 = new Intent(Intent.ACTION_CALL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent1.setData(data);
                    getActivity().startActivity(intent1);

                }
                break;
        }
    }

    @Override
    public boolean onRVItemLongClick(ViewGroup parent, View itemView, int position) {
//        Toast.makeText(getActivity(), "长按了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }


    public void getData() {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .getExpressList(userToken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
//                            super.onNext(json);
                            return;
                        }
                        JsonObject datajson = json.getAsJsonObject("data")
                                .getAsJsonObject();
                        String strdata = datajson.toString();

                        CarryOutListInfo[] list  = new Gson().fromJson(datajson.get("list").toString(),CarryOutListInfo[].class);

                        mData.clear();
                        if(list!=null) {
                            for (int i =0;i<list.length;i++)
                            {
                                CarryOutListInfo info = list[i];
                                mData.add(info);
                            }
//                            mData.addAll(list);
                        }
                        if(mData.size()>0)
                        {

                            getActivity().runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    //更新UI
                                    ll_nodata.setVisibility(View.GONE);
                                    mDataRv.setVisibility(View.VISIBLE);
                                }

                            });
                        }else{
                            getActivity().runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    //更新UI
                                    ll_nodata.setVisibility(View.VISIBLE);
                                    mDataRv.setVisibility(View.GONE);
                                }

                            });
                        }
                        mAdapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }

}
